import config from '../config';
const server = config.API_PREFIX;

const globalReqOptions = {
  success: e => {
    console.log(e);
  },
  fail: err => {
    console.log('REQ FAIL:', err);
  },
  complete: () => {
    wx.hideLoading();
  }
};

function req(url, options) {
  const token = wx.getStorageSync(config.TOKEN_KEY);
  const reqHeader = options.header || {};
  let optSuccess = null;

  if (!options.noToken) {
    reqHeader.token = token;
  }

  if (options.success) {
    optSuccess = options.success;
  }

  const op = {
    ...globalReqOptions,
    ...options,
    url: server + url,
    header: reqHeader,
    success: (res) => {
      if (res.data.code !== 0) {
        console.log('REQ ERROR:', res.data);
      }
      optSuccess && optSuccess(res);
    }
  };

  if (!options.noLoading) {
    wx.showLoading({
      title: '加载中...'
    });
  }

  return wx.request(op);
}

export default req;
